<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <crudOperation :permission="permission">
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          @click="submit()"
        >
          保存
        </el-button>
      </crudOperation>
      <!--表格渲染-->
      <el-form
        ref="form"
        :model="crud.order"
        :rules="rules"
        size="small"
        label-width="100px"
      >
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="配置编码" prop="code">
              <el-input
                v-model="crud.order.code"
                disabled
                style="width:  100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="配置名称" prop="name">
              <el-input v-model="crud.order.name" style="width:  100%" />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="6">
            <el-form-item label="数量">
              <el-input
                v-model="crud.order.quantity"
                type="Number"
                style="width:  100%"
              />
            </el-form-item>
          </el-col> -->

          <el-col :span="6">
            <el-form-item label="状态">
              <el-select
                v-model="crud.order.status"
                placeholder="请选择"
                style="width:  100%"
              >
                <el-option
                  v-for="(item, index) in dict.common_status"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注">
              <el-input
                v-model="crud.order.remark"
                type="textarea"
                style="width:  100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row> </el-row>

        <el-divider content-position="left" style="width:  100%"
          >选择</el-divider
        >

        <el-row>
          <!-- <div class="group" v-if="crud.order.type == 2">
            <div>
              <H3>活动商品列表</H3>
              <el-button
                class="filter-item"
                size="mini"
                type="primary"
                @click="toAdd"
              >
                新增
              </el-button>
            </div>
            <el-table ref="tableB" stripe border v-if="crud.order.type == 2"  v-loading="crud.loading" :row-class-name="crud.tableRowClassName"
                      :data="bomList || []"
                      size="small" style="width: 100%;"
                      :show-summary="true"
                      sortable="custom"
                      @sort-change="crud.sortChange"
                      @selection-change="crud.selectionChangeHandler"
                      @row-dblclick="crud.dbClick">
              <el-table-column :render-header="crud.renderHeader" type="selection" width="60" />
              <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
              <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCode')" prop="goodsCode" label="商品编码" />
              <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsName')" prop="goodsName" label="商品名称" width="200">
                <template slot-scope="scope">
                  <span v-if="!scope.row.isSelected">{{ scope.row.goodsName }}</span>
                  <jtg-select-plus v-else ref="productRef"
                                   v-model="scope.row.goodsId"
                                   type="1"
                                   :customerId="crud.order.customerId"
                                   :initValue="scope.row.goodsName"
                                   :buyChannel="crud.order.buyChannel"
                                   @remoteMethod="getValue($event,scope.$index)"
                                   @change="crud.productChange($event,scope)"
                                   url="productList"/>
                </template>
              </el-table-column>
              <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('firstUnitName')" prop="firstUnitName" label="计量单位" />
                <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCount')" prop="goodsCount" label="数量" >
                  <template slot-scope="scope">
                    <span v-if="!scope.row.isSelected">{{ scope.row.goodsCount }}</span>
                    <el-input v-if="scope.row.isSelected"
                              maxlength="12"
                              @input.native="crud.inuptCount(scope, 'taxPrice')"
                              v-model.lazy="scope.row.goodsCount"
                              style="width: 100%"/>
                  </template>
                </el-table-column>
              <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('boxCount')" prop="boxCount" label="箱数" />
              <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxPrice')" prop="taxPrice" label="含税单价" >
                <template slot-scope="scope">
                  <span v-if="!scope.row.isSelected">{{ scope.row.taxPrice }}</span>
                  <el-input v-if="scope.row.isSelected"
                            maxlength="12"
                            @input.native="crud.inuptCount(scope, 'taxPrice')"
                            v-model.lazy="scope.row.taxPrice"
                            style="width: 100%"/>
                </template>
              </el-table-column>
              <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount" label="含税金额" >
                <template slot-scope="scope">
                  <span >{{ scope.row.taxAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxPrice')" prop="taxPrice" label="含税单价" >
                <template slot-scope="scope">
                  <span >{{ scope.row.taxPrice }}</span>
                </template>
              </el-table-column>
              <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxBoxPrice')" prop="taxBoxPrice" label="含税箱价" >
                <template slot-scope="scope">
                  <span >{{ scope.row.taxBoxPrice }}</span>
                </template>
              </el-table-column>
              <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('tax')" prop="tax" label="税额" >
                <template slot-scope="scope">
                  <span >{{ scope.row.tax }}</span>
                </template>
              </el-table-column>
              <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注" width="200">
                <template slot-scope="scope">
                  <span v-if="!scope.row.isSelected">{{ scope.row.remark }}</span>
                  <el-input v-if="scope.row.isSelected"
                            type="textarea"
                            :rows="2"
                            v-model.lazy="scope.row.remark"
                            style="width: 100%"/>
                </template>
              </el-table-column>
              <el-table-column :render-header="crud.renderHeader"  label="操作"   align="center">
                <template slot-scope="scope">
                  <el-button
                    slot="reference" class="el-icon-delete opration_icon_btn"
                    :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'INVALID'"
                    style="border: none;width: auto;height: auto"
                    @click="delAddRow('bomList',scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div> -->
          <div class="group" v-if="crud.order.type == '1'">
            <!-- 满赠 -->
            <el-row>
              <!-- <el-col :span="6">
                <el-form-item label="达成类型">
                  <el-select v-model="crud.data.salesPointsRuleDetailDtos[0].reachType" :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'INVALID'"  @change="pushInfo" class="edit-input" placeholder="请选择"       style="width:  100%">
                    <el-option
                      v-for="(item,index) in dict.t_sales_promotion_reach_type"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col> -->
              <!-- <el-col :span="6">
                <el-form-item label="满赠方式">
                  <el-select
                    v-model="crud.data.salesPointsRuleDetailDtos[0].reachWay"
                    :disabled="
                      crud.order.orderStatus === 'PASS' ||
                        crud.order.orderStatus === 'INVALID'
                    "
                    @change="pushInfo"
                    class="edit-input"
                    placeholder="请选择"
                    style="width:  100%"
                  >
                    <el-option
                      v-for="(item, index) in dict.t_sales_promotion_reach_way"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col> -->
            </el-row>
            <el-row>
              <el-form-item label="积分配置">
                <!-- <el-col
                  :span="12"
                  v-if="crud.data.salesPointsRuleDetailDtos[0].reachWay == 1"
                >
                  <div>
                    <el-checkbox v-model="checked" disabled>阶梯</el-checkbox>
                  </div>
                  <div class="flex-left">
                    <div
                      class="flexs-cen"
                      v-for="(item, index) in crud.data
                        .salesPointsRuleDetailDtos"
                    >
                      <el-input
                        style="width: 40%"
                        placeholder="请输入"
                        @change="
                          val => {
                            isNum(item, index);
                          }
                        "
                        @input="changeInput"
                        v-model="item.quantity"
                      >
                        <template slot="prepend"
                          >满</template
                        >
                      </el-input>
                      <el-input
                        style="width: 40%"
                        placeholder="请输入"
                        @change="isGiftNum(item, index)"
                        @input="changeInput"
                        v-model="item.points"
                      >
                        <template slot="prepend"
                          >赠</template
                        >
                      </el-input>
                      <el-select
                        v-model="
                          crud.data.salesPointsRuleDetailDtos[index].resultType
                        "
                        @input="changeInput"
                        class="edit-input"
                        placeholder="请选择"
                        style="width: 80px"
                      >
                        <el-option
                          v-for="(item, index) in resultList"
                          :key="index"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <img
                        src="@/assets/images/add@2x.png"
                        v-if="crud.order.orderStatus !== 'PASS'"
                        @click="handleAdd"
                        style="width: 30px;cursor: pointer"
                      />
                      <img
                        src="@/assets/images/delete@2x.png"
                        v-if="crud.order.orderStatus !== 'PASS' && index !== 0"
                        @click="handledel(index)"
                        style="width: 30px;cursor: pointer"
                      />
                    </div>
                  </div>
                </el-col> -->
                <el-col
                  :span="12"

                >
                  <!-- 满赠方式，每满  v-if="crud.data.salesPointsRuleDetailDtos[0].reachWay == 2"-->
                  <div>
                    <el-checkbox v-model="checked" disabled>每满</el-checkbox>
                  </div>
                  <div class="flex-right">
                    <div
                      class="flexs-cen"
                      v-for="(item, index) in crud.data
                        .salesPointsRuleDetailDtos"
                    >
                      <el-input
                        style="width: 40%"
                        @input="changeInput"
                        placeholder="请输入"
                        v-model="item.quantity"
                      >
                        <template slot="prepend"
                          >满</template
                        >
                      </el-input>
                      <!-- <el-select
                        v-model="
                          crud.data.salesPointsRuleDetailDtos[index].configUnit
                        "
                        @change="$event => setResultType(index, $event)"
                        disabled
                        class="edit-input"
                        placeholder="请选择"
                        style="width: 100px"
                      >
                        <el-option
                          v-for="(item, index) in resultList"
                          :key="index"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select> -->
                      <div>元</div>
                      <el-input
                        style="width: 40%"
                        @input="changeInput"
                        placeholder="请输入"
                        v-model="item.points"
                      >
                        <template slot="prepend"
                          >赠</template
                        >
                      </el-input>
                    </div>
                  </div>
                </el-col>
              </el-form-item>
            </el-row>
          </div>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import crudIntegralConfig from "@/api/erp/points";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import Treeselect from "@riophae/vue-treeselect";
import { getAreaTree } from "@/api/erp/basCustomerArea";
import { getDepts } from "@/api/system/dept";
import { getCustomerTypeTree } from "@/api/erp/basCustomerType";
import jtgSelectPlus from "@/components/select/JtgSelectPlusSale";
import JtgTree from "@/components/Tree/JtgTreePlus";
import Vue from "vue";
import { removeDetail } from "@/api/erp/salesPromotion";
import { passOrReject } from "@/api/erp/salesPromotion";
import { getBasGoodsTagList } from "@/api/erp/basGoodsTag";
import jDialog from "@/components/jDialog/jDialog";
import { getToken } from "@/utils/auth";
import request from "@/utils/request";
import addBatch from "@/components/addBatch/addBatch.vue";
// crud交由presenter持有
const defaultCrud = CRUD({
  title: "积分配置明细",
  name: "integralConfigDetail",
  url: "/api/salesPointsRule/detail",
  dicts: ["common_order_status", "common_status"],
  sort: "id,desc",
  optShow: {
    add: false,
    edit: false,
    del: false,
    download: false,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: false,
    reject: false
  },
  params() {
    const href = location.href.split("/");
    if (href[5].includes("copyId")) {
      return {
        id: 0
      };
    } else {
      return {
        id: href[href.length - 1] == "add" ? 0 : href[href.length - 1],
        page: 0,
        size: 999
      };
    }
  },
  crudMethod: { ...crudIntegralConfig }
});
const defaultForm = {
  code: "",
  configMethod: 1,
  configUnit: "元",
  createTime: "",
  createUserCode: "",
  createUserId: 0,
  createUserName: "",
  id: 0,
  name: "",
  remark: "",
  salesPointsRuleDetailDtos: [],
  status: 0,
  type: 3, //1订单, 2充值, 3签到 mo
  updateTime: "",
  updateUserCode: "",
  updateUserId: 0,
  updateUserName: ""
};
export default {
  name: "integralConfigDetail",
  components: {
    addBatch,
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    Treeselect,
    JtgTree,
    jtgSelectPlus,
    jDialog
  },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: [
    "t_sales_promotion_type",
    "common_status",
    "t_sales_promotion_customer_group_type",
    "t_bas_customer_is_contact",
    "common_yes_or_no",
    "t_sales_promotion_channel_type",
    "t_sales_promotion_promotion_properties",
    "common_order_status",
    "t_sales_promotion_reach_type",
    "common_order_status",
    "t_bas_customer_channel_type",
    "t_sales_promotion_reach_way"
  ],
  data() {
    return {
      exceptCustomer: {
        customerId: null,
        customerCode: null,
        customerName: null,
        orderId: this.crud.order.id
      },
      importCustomer: {
        exceptCustomer: {
          title: "导入例外客户",
          action: "/api/salesPromotion/importExceptCustomer"
        },
        customerGroup: {
          title: "导入客户群",
          action: "/api/salesPromotion/importCustomerGroup"
        }
      },
      currentImport: {},
      addCustomerGroup: false,
      headers: { Authorization: getToken() },
      saleSystemIds: "",
      addExceptCustomer: "",
      customerTypeIds: [],
      customerAreaIds: [],
      showExceptCustomer: false,
      showCustomerGroup: false,
      currentCustomer: {},
      checked: true,
      isShow: true,
      dataExtent: [],
      minusList: [],
      specialList: [],
      exceptCustomerIds: [],
      saleSystemName: "",
      giftList: [],
      showAddBatch: false,
      resultList: [{ label: "次", value: 1 }, { label: "元", value: 2 }],
      activityList: [],
      giftList01: [],
      isGiftTag: {},
      discountList: [],
      bomList: [],
      salesPointsRuleDetailDtos: [],
      activeName: "activity",
      permission: {
        add: ["admin", "salesPromotionDetail:add"],
        edit: ["admin", "salesPromotionDetail:edit"]
      },
      isImport: false,
      showAddBatchDialog: false,
      rules: {
        name: [{ required: true, message: "配置名称不能为空", trigger: "blur" }]
      }
      // addRowData: {
      //   code: null,
      //   configMethod: 0,
      //   configUnit: null,
      //   createTime: null,
      //   createUserCode: null,
      //   createUserId: 0,
      //   createUserName: null,
      //   id: 0,
      //   name: null,
      //   remark: null,
      //   salesPointsRuleDetailDtos: [],
      //   status: 0,
      //   type: 3, //1订单, 2充值, 3签到 mo
      //   updateTime: null,
      //   updateUserCode: null,
      //   updateUserId: 0,
      //   updateUserName: null
      // }
    };
  },
  watch: {},
  destroyed() {
    // Cookies.set("customerForm_" + this.id, JSON.stringify(this.form))
    if (!this.saveFlag) {
      // this.crud.order.detailList = [
      //   {
      //     bomList: this.bomList || [],
      //     discountList: this.discountList || [],
      //     giftList: this.giftList || [],
      //     minusList: this.minusList || [],
      //     salesPointsRuleDetailDtos: this.salesPointsRuleDetailDtos || [],
      //     specialList: this.specialList || []
      //   }
      // ];

      this.crud.setItemInfo("integralConfigDetailAdd");
    }
  },
  handleError(err, file, fileList) {
    this.crud.notify(
      " -_- !~~ 服务器开小差了，稍后重试",
      CRUD.NOTIFICATION_TYPE.WARNING
    );
  },
  created() {
    const href = location.href.split("/");

    if (href[5].includes("copyId")) {
      let strs = this.$route.params.id.split("=");
      this.crud.toGetCopyInfo(strs[1], "integralConfigDetail");
      // this.crud.order.orderStatus = "SAVE";
    }
    if (this.$route.params.id == "add") {
      // let _form = JSON.parse(localStorage.getItem("integralConfigDetailAdd"));
      // if (_form) {
      //   this.crud.order = _form;
      //   this.crud.data = _form.detailList;
      //   this.specialList = this.crud.data.specialList || [];
      //   this.minusList = this.crud.data.minusList || [];
      //   this.giftList = this.crud.data.giftList || [];
      //   this.discountList = this.crud.data.discountList || [];
      //   this.bomList = this.crud.data.bomList || [];
      //   this.salesPointsRuleDetailDtos =
      //     this.crud.data.salesPointsRuleDetailDtos || [];
      //   if (this.crud.data.salesPointsRuleDetailDtos.length === 0) {
      //     this.crud.data.salesPointsRuleDetailDtos = [
      //       {
      //         id: null,
      //         code: "",
      //         quantity: null,
      //         reachWay: 2,
      //         reachType: null,
      //         points: null
      //       }
      //     ];
      //   } else {
      //     this.crud.data.reachType = this.crud.data.salesPointsRuleDetailDtos[0].reachType;
      //     this.crud.data.reachWay = this.crud.data.salesPointsRuleDetailDtos[0].reachWay;
      //     this.salesPointsRuleDetailDtos =
      //       this.crud.data.salesPointsRuleDetailDtos || [];
      //     console.log(this.crud.data.reachType);
      //   }
      // } else {
      this.specialList = [];
      this.minusList = [];
      this.giftList = [];
      this.discountList = [];
      this.bomList = [];
      this.crud.data.salesPointsRuleDetailDtos = [
        {
          id: null,
          orderId: "",
          points: null,
          reachWay: 2,
          quantity: null
        }
      ];
      this.crud.order = {
        code: "",
        configMethod:1,
        configUnit: "元",
        createTime: "",
        createUserCode: "",
        createUserId: 0,
        createUserName: "",
        id: 0,
        name: "",
        remark: "",
        salesPointsRuleDetailDtos: [],
        status: 0,
        type: "1", //1订单, 2充值, 3签到 mo
        updateTime: "",
        updateUserCode: "",
        updateUserId: 0,
        updateUserName: ""
      };
      // }
    } else {
      const id = this.$route.params.id;
      this.getOneById(id);
      // }
    }
    // getBasGoodsTagList({ size: 999 }).then(res => {
    //   this.isGiftTag = res.content.find(
    //     item => item.name === "赠品" || item.name === "促销酒"
    //   );
    // });
  },
  activated() {
    // const href = location.href.split("/");
    // console.log("activated href", href);
    // if (href[5] != null &&href[5] !=''&& href[5] != 0) {
    //   this.getOneById(href[5]);
    // }
  },
  mounted() {},
  updated() {
    // this.$nextTick(() => {
    //   this.$refs.table.doLayout()
    // })
  },
  methods: {
    getOneById(id) {
      crudIntegralConfig.detail({ id: id }).then(res => {
        console.log("getOneById", res);
        if (res.data) {
          this.crud.order = res.data;
        }
      });
    },
    changeInfo(e) {},
    setResultType(index, e) {
      this.$forceUpdate();
    },
    setCurrentImport(type) {
      this.currentImport = this.importCustomer[type];
      this.isImport = true;
    },
    handleError(err, file, fileList) {
      this.crud.notify(
        " -_- !~~ 服务器开小差了，稍后重试",
        CRUD.NOTIFICATION_TYPE.WARNING
      );
    },

    tabSelect(row) {
      if (this.crud.order.orderStatus !== "PASS") {
        this.$set(row, "isSelected", !row.isSelected);
      }
    },
    handleSuccess(response, file, fileList) {
      console.log("handleSuccess", response);
      if (response !== "导入成功") {
        const a = document.createElement("a");
        a.setAttribute("href", response.data.points);
        a.click();
      } else {
        this.crud.notify(response, CRUD.NOTIFICATION_TYPE.SUCCESS);
        this.$refs.upload.clearFiles();
        this.uploadDialgShow = false;
        this.crud.refresh();
      }
    },
    delAddRow(name, i) {
      const id = this[name][i].id;
      const that = this;
      if (id) {
        removeDetail({ id, type: this.crud.order.type }).then(res => {
          if (res.status === 200) {
            that[name].splice(i, 1);
          } else {
            this.$message({
              type: "error",
              message: res.msg
            });
          }
        });
      } else {
        that[name].splice(i, 1);
      }
    },
    pushInfo(e) {
      if (e === 2) {
        this.$set(
          this.crud.data.salesPointsRuleDetailDtos,
          "0",
          this.crud.data.salesPointsRuleDetailDtos[0]
        );
      }
      this.$forceUpdate();
      this.isShow = true;
    },
    getTime(date = new Date()) {
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var minute = date.getMinutes();
      minute = minute < 10 ? "0" + minute : minute;
      var second = date.getSeconds();
      second = second < 10 ? "0" + second : second;
      // +' '+h+':'+minute+':'+second;
      return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.afterRefresh]() {
      setTimeout(() => {
        // this.specialList = this.crud.data.specialList || [];
        // this.minusList = this.crud.data.minusList || [];
        // this.giftList = this.crud.data.giftList || [];
        // this.discountList = this.crud.data.discountList || [];
        // this.bomList = this.crud.data.bomList || [];
        // this.salesPointsRuleDetailDtos =
        //   this.crud.data.salesPointsRuleDetailDtos || [];
        // this.giftList01 = [];
        // this.activityList = [];
        // if (this.crud.data.giftList) {
        //   for (let i = 0; i < this.crud.data.giftList.length; i++) {
        //     if (this.crud.data.giftList[i].isGift) {
        //       this.giftList01.push(this.crud.data.giftList[i]);
        //     } else {
        //       this.activityList.push(this.crud.data.giftList[i]);
        //     }
        //   }
        // }
        // if (this.crud.order.exceptCustomerIds)
        //   this.exceptCustomerIds = this.crud.order.exceptCustomerIds.split(",");
        // if (this.crud.order.customerTypeList)
        //   this.customerTypeIds = this.crud.order.customerTypeList.map(
        //     item => item.customerTypeId
        //   );
        // if (this.crud.order.customerAreaList)
        //   this.customerAreaIds = this.crud.order.customerAreaList.map(
        //     item => item.customerAreaId
        //   );
        // if (this.crud.order.saleSystemList) {
        //   this.saleSystemIds = this.crud.order.saleSystemList
        //     .map(item => item.saleSystemId)
        //     .join(",");
        //   this.saleSystemName = this.crud.order.saleSystemList
        //     .map(item => item.saleSystemName)
        //     .join(",");
        // }
      });
      return true;
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {},
    getValue(e) {
      this.query.startTime = this.dataExtent[0];
      this.query.endTime = this.dataExtent[1];
    },
    getInput(e, name, i) {
      if (this.crud.data) {
        if (e) {
          this.crud.data[i].goodsName = "";
          this.crud.data[i].goodsId = e;
        } else {
          this.crud.data[i].goodsName = "";
          this.crud.data[i].goodsId = null;
        }
      }
    },
    addBatchGoods(list) {
      list.forEach(item => {
        //去重
        if (this.activeName === "activity") {
          const index = this.activityList.some(
            val => item.goodsId === val.goodsId
          );
          if (!index) {
            item.isRequired = 0;
            const goods = Object.assign(
              {
                isSelected: false,
                isGift: 0,
                id: null,
                saleTaxPrice: null,
                promotionTaxPrice: 0,
                goodsCount: 0,
                orderId: null,
                goodsId: null,
                goodsCode: null,
                goodsName: null,
                barcode: null,
                boxBarcode: null,
                helpSign: null,
                model: null,
                goodsBrandId: null,
                goodsBrandCode: null,
                goodsBrandName: null,
                goodsTypeId: null,
                goodsTypeCode: null,
                goodsTypeName: null,
                goodsTagId: null,
                goodsTagCode: null,
                goodsTagName: null,
                taxId: null,
                taxCode: null,
                taxName: null,
                taxRate: null,
                firstUnitId: null,
                firstUnitCode: null,
                firstUnitName: null,
                firstUnitCount: null,
                effectGoodsCount: null,
                cutOffGoodsCount: null,
                taxPrice: null,
                noTaxPrice: null,
                taxBoxPrice: null,
                noTaxBoxPrice: null,
                seq: null,
                remark: null,
                createUserId: null,
                createUserCode: null,
                createUserName: null,
                createTime: null,
                updateUserId: null,
                updateUserCode: null,
                updateUserName: null,
                updateTime: null,
                isRequired: 0
              },
              item
            );
            this.toAdd(goods);
          }
        } else {
          const index = this.giftList01.some(
            val => item.goodsId === val.goodsId
          );
          if (!index) {
            item.isRequired = 0;
            const goods = Object.assign(
              {
                isSelected: false,
                isGift: 1,
                id: null,
                saleTaxPrice: null,
                promotionTaxPrice: 0,
                goodsCount: 0,
                orderId: null,
                goodsId: null,
                goodsCode: null,
                goodsName: null,
                barcode: null,
                boxBarcode: null,
                helpSign: null,
                model: null,
                goodsBrandId: null,
                goodsBrandCode: null,
                goodsBrandName: null,
                goodsTypeId: null,
                goodsTypeCode: null,
                goodsTypeName: null,
                goodsTagCode: null,
                goodsTagName: null,
                taxId: null,
                taxCode: null,
                taxName: null,
                taxRate: null,
                firstUnitId: null,
                firstUnitCode: null,
                firstUnitName: null,
                firstUnitCount: null,
                effectGoodsCount: null,
                cutOffGoodsCount: null,
                taxPrice: null,
                noTaxPrice: null,
                taxBoxPrice: null,
                noTaxBoxPrice: null,
                seq: null,
                remark: null,
                createUserId: null,
                createUserCode: null,
                createUserName: null,
                createTime: null,
                updateUserId: null,
                updateUserCode: null,
                updateUserName: null,
                updateTime: null,
                isGiftPaperBox: 0,
                goodsTagId: null,
                advanceRate: this.crud.order.advanceRate,
                expenseRate: this.crud.order.expenseRate
              },
              item
            );
          }
        }
      });
    },
    afterChangeGoods(goods) {
      this.showAddBatchDialog = false;
      //去重，已经去重
      let arr = this.crud.data.map(detail => detail.goodsId);
      let _goods = [];
      let result = [];
      goods.forEach(good => {
        // if(!arr.includes(goods.goodsId)){
        good.isSelected = true;
        this.crud.data.push(good);
        // }
      });
      // this.calcuForm()
    },
    changeRate(type) {
      if (Number(this.crud.order[type]) > 100) {
        this.$message.error("比例不允许大于100");
        this.crud.order[type] = 100;
      }
      if (type === "advanceRate") {
        const expenseRate = 100 - Number(this.crud.order.advanceRate);
        this.$set(this.crud.order, "expenseRate", expenseRate);
      } else {
        const advanceRate = 100 - Number(this.crud.order.expenseRate);
        this.$set(this.crud.order, "advanceRate", advanceRate);
      }
    },
    setExceptCustomer(e) {
      this.exceptCustomer.customerId = e.id;
      this.exceptCustomer.customerCode = e.code;
      this.exceptCustomer.customerName = e.name;
    },
    setCustomerGroup(e) {
      this.currentCustomer.customerId = e.id;
      this.currentCustomer.customerCode = e.code;
      this.currentCustomer.customerName = e.name;
    },
    toAddList() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //校验通过
          this.showAddBatchDialog = true;
        } else {
          // if (!this.crud.order.customerId) {
          //   this.$message.error("请先选择客户")
          // }
          // if (!this.crud.order.type) {
          //   this.$message.error("请先选择销售单类型")
          // }
        }
      });
    },
    getInfo(e) {
      this.crud.order.warehouseId = e.warehouseId;
      this.crud.order.deptId = e.deptId;
      this.crud.order.userId = e.userId;

      this.crud.order.carId = e.carId;
      this.crud.order.loadCode = e.loadCode;
      this.crud.order.loadTime = e.loadTime;

      this.crud.order.driverUserId = e.driverUserId;
      this.crud.order.followUserId = e.followUserId;
      this.crud.order.printStatus = e.printStatus;

      this.crud.order.printCount = e.printCount;
      this.crud.order.acceptStatus = e.acceptStatus;
      this.crud.order.cancelStatus = e.cancelStatus;
      this.crud.order.pickSeq = e.pickSeq;
      this.crud.order.warehouseId = e.warehouseId;
      this.crud.order.contactName = e.contactName;
      this.crud.order.contactPhone = e.contactPhone;
      this.crud.order.deliveryAddress = e.deliveryAddress;
      this.crud.order.address = e.address;
    },
    // 新增
    toAdd(e) {
      // if(!this.crud.order.customerId){
      //   this.$message({
      //     message: '请先选择客户',
      //     type: 'error'
      //   })
      //   return false
      // }
      if (!e.goodsId) e = null;
      this.$nextTick(() => {
        if (this.crud.order.type == 1) {
          this.specialList.push(
            e || {
              isSelected: true,
              id: null,
              promotionTaxPrice: 0,
              goodsCount: 0,
              saleTaxPrice: null,
              orderId: null,
              goodsId: null,
              goodsCode: null,
              goodsName: null,
              barcode: null,
              boxBarcode: null,
              helpSign: null,
              model: null,
              goodsBrandId: null,
              goodsBrandCode: null,
              goodsBrandName: null,
              goodsTypeId: null,
              goodsTypeCode: null,
              goodsTypeName: null,
              goodsTagId: null,
              goodsTagCode: null,
              goodsTagName: null,
              taxId: null,
              taxCode: null,
              taxName: null,
              taxRate: null,
              firstUnitId: null,
              firstUnitCode: null,
              firstUnitName: null,
              firstUnitCount: null,
              effectGoodsCount: null,
              cutOffGoodsCount: null,
              taxPrice: null,
              noTaxPrice: null,
              taxBoxPrice: null,
              noTaxBoxPrice: null,
              seq: null,
              remark: null,
              createUserId: null,
              createUserCode: null,
              createUserName: null,
              createTime: null,
              updateUserId: null,
              updateUserCode: null,
              updateUserName: null,
              updateTime: null,
              promotionTaxBoxPrice: null
            }
          );
        } else if (this.crud.order.type == 2) {
          this.bomList.push(
            e || {
              isSelected: true,
              id: null,
              saleTaxPrice: null,
              promotionTaxPrice: 0,
              goodsCount: 0,
              orderId: null,
              goodsId: null,
              goodsCode: null,
              goodsName: null,
              barcode: null,
              boxBarcode: null,
              helpSign: null,
              model: null,
              goodsBrandId: null,
              goodsBrandCode: null,
              goodsBrandName: null,
              goodsTypeId: null,
              goodsTypeCode: null,
              goodsTypeName: null,
              goodsTagId: null,
              goodsTagCode: null,
              goodsTagName: null,
              taxId: null,
              taxCode: null,
              taxName: null,
              taxRate: null,
              firstUnitId: null,
              firstUnitCode: null,
              firstUnitName: null,
              firstUnitCount: null,
              effectGoodsCount: null,
              cutOffGoodsCount: null,
              taxPrice: null,
              noTaxPrice: null,
              taxBoxPrice: null,
              noTaxBoxPrice: null,
              seq: null,
              remark: null,
              createUserId: null,
              createUserCode: null,
              createUserName: null,
              createTime: null,
              updateUserId: null,
              updateUserCode: null,
              updateUserName: null,
              updateTime: null
            }
          );
        } else if (this.crud.order.type == 3) {
          if (this.activeName === "activity") {
            this.activityList.push(
              e || {
                isSelected: true,
                isGift: 0,
                id: null,
                saleTaxPrice: null,
                promotionTaxPrice: 0,
                goodsCount: 0,
                orderId: null,
                goodsId: null,
                goodsCode: null,
                goodsName: null,
                barcode: null,
                boxBarcode: null,
                helpSign: null,
                model: null,
                goodsBrandId: null,
                goodsBrandCode: null,
                goodsBrandName: null,
                goodsTypeId: null,
                goodsTypeCode: null,
                goodsTypeName: null,
                goodsTagId: null,
                goodsTagCode: null,
                goodsTagName: null,
                taxId: null,
                taxCode: null,
                taxName: null,
                taxRate: null,
                firstUnitId: null,
                firstUnitCode: null,
                firstUnitName: null,
                firstUnitCount: null,
                effectGoodsCount: null,
                cutOffGoodsCount: null,
                taxPrice: null,
                noTaxPrice: null,
                taxBoxPrice: null,
                noTaxBoxPrice: null,
                seq: null,
                remark: null,
                createUserId: null,
                createUserCode: null,
                createUserName: null,
                createTime: null,
                updateUserId: null,
                updateUserCode: null,
                updateUserName: null,
                updateTime: null,
                isRequired: 0
              }
            );
          } else {
            this.giftList01.push(
              e || {
                isSelected: true,
                isGift: 1,
                id: null,
                saleTaxPrice: null,
                promotionTaxPrice: 0,
                goodsCount: 0,
                orderId: null,
                goodsId: null,
                goodsCode: null,
                goodsName: null,
                barcode: null,
                boxBarcode: null,
                helpSign: null,
                model: null,
                goodsBrandId: null,
                goodsBrandCode: null,
                goodsBrandName: null,
                goodsTypeId: null,
                goodsTypeCode: null,
                goodsTypeName: null,
                goodsTagCode: null,
                goodsTagName: null,
                taxId: null,
                taxCode: null,
                taxName: null,
                taxRate: null,
                firstUnitId: null,
                firstUnitCode: null,
                firstUnitName: null,
                firstUnitCount: null,
                effectGoodsCount: null,
                cutOffGoodsCount: null,
                taxPrice: null,
                noTaxPrice: null,
                taxBoxPrice: null,
                noTaxBoxPrice: null,
                seq: null,
                remark: null,
                createUserId: null,
                createUserCode: null,
                createUserName: null,
                createTime: null,
                updateUserId: null,
                updateUserCode: null,
                updateUserName: null,
                updateTime: null,
                isGiftPaperBox: 0,
                goodsTagId: null,
                advanceRate: this.crud.order.advanceRate,
                expenseRate: this.crud.order.expenseRate
              }
            );
          }
        } else if (this.crud.order.type == 4) {
          this.minusList.push(
            e || {
              isSelected: true,
              id: null,
              saleTaxPrice: null,
              promotionTaxPrice: 0,
              goodsCount: 0,
              orderId: null,
              goodsId: null,
              goodsCode: null,
              goodsName: null,
              barcode: null,
              boxBarcode: null,
              helpSign: null,
              model: null,
              goodsBrandId: null,
              goodsBrandCode: null,
              goodsBrandName: null,
              goodsTypeId: null,
              goodsTypeCode: null,
              goodsTypeName: null,
              goodsTagId: null,
              goodsTagCode: null,
              goodsTagName: null,
              taxId: null,
              taxCode: null,
              taxName: null,
              taxRate: null,
              firstUnitId: null,
              firstUnitCode: null,
              firstUnitName: null,
              firstUnitCount: null,
              effectGoodsCount: null,
              cutOffGoodsCount: null,
              taxPrice: null,
              noTaxPrice: null,
              taxBoxPrice: null,
              noTaxBoxPrice: null,
              seq: null,
              remark: null,
              createUserId: null,
              createUserCode: null,
              createUserName: null,
              createTime: null,
              updateUserId: null,
              updateUserCode: null,
              updateUserName: null,
              updateTime: null
            }
          );
        } else if (this.crud.order.type == 5) {
          this.discountList.push(
            e || {
              isSelected: true,
              id: null,
              saleTaxPrice: null,
              promotionTaxPrice: 0,
              goodsCount: 0,
              orderId: null,
              goodsId: null,
              goodsCode: null,
              goodsName: null,
              barcode: null,
              boxBarcode: null,
              helpSign: null,
              model: null,
              goodsBrandId: null,
              goodsBrandCode: null,
              goodsBrandName: null,
              goodsTypeId: null,
              goodsTypeCode: null,
              goodsTypeName: null,
              goodsTagId: null,
              goodsTagCode: null,
              goodsTagName: null,
              taxId: null,
              taxCode: null,
              taxName: null,
              taxRate: null,
              firstUnitId: null,
              firstUnitCode: null,
              firstUnitName: null,
              firstUnitCount: null,
              effectGoodsCount: null,
              cutOffGoodsCount: null,
              taxPrice: null,
              noTaxPrice: null,
              taxBoxPrice: null,
              noTaxBoxPrice: null,
              seq: null,
              remark: null,
              createUserId: null,
              createUserCode: null,
              createUserName: null,
              createTime: null,
              updateUserId: null,
              updateUserCode: null,
              updateUserName: null,
              updateTime: null
            }
          );
        }
      });
    },
    productChange($event, scope) {
      $event.goodsTagId = this.isGiftTag.id;
      $event.goodsTagName = this.isGiftTag.name;
      $event.goodsTagCode = this.isGiftTag.code;
      this.crud.productChange($event, scope);
    },
    submit() {
      let that = this;
      try {
        this.$refs["form"].validate(valid => {
          if (!valid) {
            return;
          }
          if (this.crud.data.salesPointsRuleDetailDtos) {
            console.log(
              "this.crud.data.salesPointsRuleDetailDtos",
              this.crud.data.salesPointsRuleDetailDtos
            );
            this.crud.data.salesPointsRuleDetailDtos.forEach(item => {
              item.points = this.crud.data.salesPointsRuleDetailDtos[0].points;
              item.quantity = this.crud.data.salesPointsRuleDetailDtos[0].quantity;
            });
          }
          this.crud.order.type = "1"; //消费
          this.crud.order.salesPointsRuleDetailDtos = this.crud.data.salesPointsRuleDetailDtos;
          that.crud.loadingOpen();
          let params = this.crud.order;
          crudIntegralConfig
            .add(params)
            .then(res => {
              if (res.success) {
                this.crud.order = res.data;

                let id = res.data.id;
                console.log("this.$route.params.id", this.$route.params.id);
                if (this.$route.params.id == "add") {
                  this.$store.dispatch("tagsView/delView", this.$route);
                  this.$router.push({ params: { id } });
                  this.crud.cleanItemInfo("integralConfigDetailAdd");
                }

                this.$message({
                  message: "保存成功",
                  type: "success"
                });

                that.crud.loadingClose();

                // this.crud.refresh();
              } else {
                that.crud.loadingClose();
                this.$message({
                  message: res.msg,
                  type: "warning"
                });
              }
            })
            .catch(res => {
              that.crud.loadingClose();
            });
        });
      } catch (e) {
        console.log(e);
        that.crud.loadingClose();
      }
    },

    pushExceptCustomer() {
      if (!this.crud.data.exceptCustomerList)
        this.crud.data.exceptCustomerList = [];
      const index = this.crud.data.exceptCustomerList.findIndex(
        item => item.customerId === this.exceptCustomer.customerId
      );
      console.log(this.crud.data.exceptCustomerList);
      console.log(index);
      if (index !== -1) {
        this.$message.error("该客户已存在");
        return;
      }
      this.crud.data.exceptCustomerList.push(
        Object.assign({}, this.exceptCustomer)
      );
      console.log(this.crud.data.exceptCustomerList);
      this.exceptCustomer.customerId = null;
      this.exceptCustomer.customerCode = null;
      this.exceptCustomer.customerName = null;
      this.$message.success("添加成功");
    },
    pushCustomerGroup() {
      if (this.currentCustomer.customerId === null)
        return this.$message.error("请先选择客户");
      if (!this.crud.order.customerList)
        this.$set(this.crud.order, "customerList", []);
      const index = this.crud.order.customerList.findIndex(
        item => item.customerId === this.currentCustomer.customerId
      );
      if (~index) return this.$message.error("该客户已存在");
      this.crud.order.customerList.push(
        Object.assign({}, this.currentCustomer)
      );
      this.currentCustomer.customerId = null;
      this.currentCustomer.customerCode = null;
      this.currentCustomer.customerName = null;
      this.$message.success("添加成功");
    },
    isNum(item, index) {
      item.quantity =
        index > 0
          ? item.quantity > this.salesPointsRuleDetailDtos[index - 1].quantity
            ? item.quantity
            : Number(this.salesPointsRuleDetailDtos[index - 1].quantity) + 1
          : item.quantity;
    },
    isGiftNum(item, index) {
      item.points =
        index > 0
          ? item.points > this.salesPointsRuleDetailDtos[index - 1].points
            ? item.points
            : Number(this.salesPointsRuleDetailDtos[index - 1].points) + 1
          : item.points;
    },
    inputCount(scope, type) {
      if (type === "promotionTaxPrice") {
        const promotionTaxBoxPrice = (
          Number(scope.row.promotionTaxPrice) * Number(scope.row.boxUnitCount)
        ).toFixed(2);
        scope.row.promotionNoTaxPrice =
          scope.row.promotionTaxPrice / (1 + scope.row.taxRate / 100);
        scope.row.promotionNoTaxBoxPrice =
          Number(scope.row.promotionNoTaxPrice) *
          Number(scope.row.boxUnitCount);
        this.$set(scope.row, "promotionTaxBoxPrice", promotionTaxBoxPrice);
        console.log(scope.row.promotionTaxBoxPrice);
      } else if (type === "promotionTaxBoxPrice") {
        scope.row.promotionTaxPrice = (
          Number(scope.row.promotionTaxBoxPrice) /
          Number(scope.row.boxUnitCount)
        ).toFixed(2);
        scope.row.promotionNoTaxPrice =
          scope.row.promotionTaxPrice / (1 + scope.row.taxRate / 100);
        scope.row.promotionNoTaxBoxPrice =
          Number(scope.row.promotionNoTaxPrice) *
          Number(scope.row.boxUnitCount);
      }
      this.$forceUpdate();
    },
    changeInput(val) {
      this.$forceUpdate();
    },
    removeExcept(id) {
      const index = this.crud.data.exceptCustomerList.findIndex(
        item => item.customerId === id
      );
      this.crud.data.exceptCustomerList.splice(index, 1);
    },
    removeGroup(index) {
      // const index = this.crud.order.customerList.findIndex(item=>item.customerId === id)
      console.log(this.crud.order.customerList, index);
      this.crud.order.customerList.splice(index, 1);
    },
    handleAdd() {
      this.isShow = false;
      this.$nextTick(() => {
        this.isShow = true;
        let that = this;
        console.log(" this.crud.data", this.crud.data);
        let data = {
          id: null,
          code: "",
          quantity: null,
          reach_way: null,
          reach_type: null,
          points: null
        };
        that.crud.data.salesPointsRuleDetailDtos.push(data);
        let leit = JSON.stringify(that.salesPointsRuleDetailDtos);
        that.salesPointsRuleDetailDtos = JSON.parse(leit);
      });
    },
    recover(type) {
      const that = this;
      crudIntegralConfig
        .passOrReject({ ids: [this.crud.order.id], type: type })
        .then(res => {
          if (res.status === 200) {
            that.$message.success("操作成功");
            that.crud.refresh();
          }
        });
    },
    handledel(index) {
      this.isShow = false;
      let that = this;
      console.log(that);
      this.$nextTick(() => {
        this.isShow = true;
        that.crud.data.salesPointsRuleDetailDtos.splice(index, 1);
        that.salesPointsRuleDetailDtos.splice(index, 1);
        let leit = JSON.stringify(that.salesPointsRuleDetailDtos);
        that.salesPointsRuleDetailDtos = JSON.parse(leit);
      });
    },

    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
.flex-left {
  display: inline-block;
}
.flex-right {
  display: inline-block;
}
.flexs-cen {
  display: flex;
  height: 40px;
  line-height: 40px;
  align-items: center;
  justify-content: space-between;
}
.exceptCustomerBox {
  height: 500px;
  overflow: auto;
  .exceptCustomer {
    font-size: 20px;
    margin-top: 10px;
    .del {
      color: blue;
      cursor: pointer;
    }
  }
}
</style>
